from typing import Callable

from playwright.sync_api import Page, BrowserContext
from src.utils.patterns import get_url_refer
from .components.network_watcher import NetworkWatcher, NetworkData
from .components.local_storage import LocalStorage


class BrowserPage:
    def __init__(self, page: Page, context: BrowserContext):
        self.page_context = page
        self.browser_context = context
        self.network_watcher = NetworkWatcher(page=page)
        self.local_storage = LocalStorage(page=page)
        pass

    def watch(self, url_pattern: str, filters: Callable[[NetworkData], bool] = None):
        return self.network_watcher.watch(url_pattern=url_pattern, filters=filters)

    def navigate_to(self, url=''):
        self.page_context.goto(url, timeout=300000, referer=get_url_refer(url))
        self.network_watcher.setup_js_interceptor()
        pass

    def navigate_back(self):
        self.page_context.go_back()
        self.network_watcher.setup_js_interceptor()
        pass

    def navigate_forward(self):
        self.page_context.go_forward()
        self.network_watcher.setup_js_interceptor()
        pass

    def query_selector(self, selector: str):
        return self.page_context.query_selector(selector)

    def close(self):
        self.page_context.close()
        pass
